package com.bootdo.clouddo.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class DoubanUtils {

	
	/**
     * 向目的URL发送get请求
     * @param url       目的url
     * @return  ResultVO
     */
	public static JSONObject getRequest(String url) throws Exception{
		//增加下面两行代码
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		CloseableHttpClient httpclient = HttpClients.custom().build();       //创建一个客户端
		//logger.info("=========>current_download_url:"+url);
		//System.out.println("=========>getting:"+url);
		String htmlString = "";         //定义返回的String变量
		//Thread.sleep(getRandom(100,500));
		long before = System.nanoTime();
		HttpGet request = new HttpGet(url); //请求资源
		CloseableHttpResponse response = httpclient.execute(request);           //得到回应
		try {
			org.apache.http.HttpEntity entity = response.getEntity();                   //获得Entity对象
			htmlString = EntityUtils.toString(entity, "utf-8");                  //将Entity对象转化为字符串
			htmlString = decodeUnicode(htmlString);
			System.out.println("end[耗时："+(System.nanoTime()-before)/1000000+"ms]");
			EntityUtils.consume(entity);                                //销毁对象
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			response.close();
		}
		return JSON.parseObject(htmlString);
    }

	public static String downloadPage(String url, Boolean isM) throws Exception {
		//增加下面两行代码
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClientBuilder httpClientBuilder = HttpClients.custom();
		CloseableHttpClient httpclient = HttpClients.custom().build();       //创建一个客户端
		//logger.info("=========>current_download_url:"+url);
		//System.out.println("=========>getting:"+url);
		String htmlString = "";         //定义返回的String变量
		//Thread.sleep(getRandom(100,500));
		long before = System.nanoTime();
		System.out.print("url:["+url+"] beginning-->");
		HttpGet request = new HttpGet(url); //请求资源
		if(isM)
			setMHeader(request);
		else
			setHeader(request);
		CloseableHttpResponse response = httpclient.execute(request);           //得到回应
		try {
			org.apache.http.HttpEntity entity = response.getEntity();                   //获得Entity对象
			htmlString = EntityUtils.toString(entity, "utf-8");                  //将Entity对象转化为字符串
			htmlString = decodeUnicode(htmlString);
			System.out.println("end[耗时："+(System.nanoTime()-before)/1000000+"ms]");
			EntityUtils.consume(entity);                                //销毁对象
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			response.close();
		}
		return htmlString;

	}

	public static void setHeader(HttpGet request) {
		request.setHeader("Connection", "keep-alive");
		request.setHeader("Accept-Encoding", "gzip, deflate, br");
		request.setHeader("Content-Type", "application/json");
		request.setHeader("Host", "frodo.douban.com");
		request.setHeader("Origin", "null");
		request.setHeader("Accept", "*");
		//request.setHeader("Accept", "*");
		//request.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		//request.setHeader("Accept-Charset", "UTF-8,utf-8;q=0.7,*;q=0.7");
		//request.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
		//request.setHeader("Cookie", "JSESSIONID=1DEB895F1074768E0A04D013E6364A2A; _ga=GA1.3.945921650.1565495158; zg_did=%7B%22did%22%3A%20%2216d686d0d333-06675ac41c23ee-1d3d6b55-1aeaa0-16d686d0d35a83%22%7D; _ga=GA1.4.945921650.1565495158; __utma=65168252.945921650.1565495158.1569462118.1569462118.1; __utmz=65168252.1569462118.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); zg_90dc219b89ee40d99689b0ed4befbe51=%7B%22sid%22%3A%201569484678244%2C%22updated%22%3A%201569484678259%2C%22info%22%3A%201569484678254%2C%22superProperty%22%3A%20%22%7B%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22%22%2C%22landHref%22%3A%20%22https%3A%2F%2Fxz.chsi.com.cn%2Fpsn%2Fpsncenter.action%22%2C%22cuid%22%3A%20%22e7d1e38bb9a5d89fb32bbe75d212182c%22%7D; aliyungf_tc=AQAAAFTUHw9NwgMACr1aZ3451jAVVp3W; CHSICC_CLIENTFLAG7=d1d63fb77f9d9201f2e02b14782c3934; CHSICC_CLIENTFLAG270=23d9bf4787f20984d175302d1f6af58f; XSRF-CCKTOKEN=b2bbc8ae6c7afc42a71bdfec15b6e190; CHSICC_CLIENTFLAG180=b3f23705f49aa1f0153b27a2a1b49236; CHSICC01=!I4trUzdF1FBbBXMGGYWrKFjgWJfD/4ixoCN2WmFZ6MKzs9dFKFB/NYRfxpBedgbMdh++leAAO/t1; acw_tc=2760823815720938954774464edea604fa9b89d008555a5e51925e4c4e1e71; _gid=GA1.4.2051107744.1572226325; __utma=229973332.945921650.1565495158.1572261516.1572261516.1; __utmc=229973332; __utmz=229973332.1572261516.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _gid=GA1.3.2051107744.1572226325; JSESSIONID=B8A217007C20954F274BD9836D609E78; yzwb_show_ewm=true; CHSICC_CLIENTFLAG310=0b261e848dcc9512888b49d02619818f; zg_0d76434d9bb94abfaa16e1d5a3d82b52=%7B%22sid%22%3A%201572508867965%2C%22updated%22%3A%201572508867994%2C%22info%22%3A%201572508867993%2C%22superProperty%22%3A%20%22%7B%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22%22%2C%22cuid%22%3A%20%22e7d1e38bb9a5d89fb32bbe75d212182c%22%2C%22landHref%22%3A%20%22https%3A%2F%2Fmy.chsi.com.cn%2Farchive%2Findex.jsp%22%7D; zg_adfb574f9c54457db21741353c3b0aa7=%7B%22sid%22%3A%201572507849288%2C%22updated%22%3A%201572509926116%2C%22info%22%3A%201571973262686%2C%22superProperty%22%3A%20%22%7B%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22%22%2C%22landHref%22%3A%20%22https%3A%2F%2Fyz.chsi.com.cn%2F%22%2C%22cuid%22%3A%20%22e7d1e38bb9a5d89fb32bbe75d212182c%22%7D");
		//request.setHeader("Host", "https://movie.douban.com");
		//request.setHeader("refer", "https://movie.douban.com");
		request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Rexxar/1.2.100 com.douban.frodo/6.23.0 iOS/13.2 model/iPhone8,1 udid/b0b995fef0fb1aa0f96defe45393202f96056959 network/wifi");
	}

	public static void setMHeader(HttpGet request) {
		request.setHeader("Connection", "keep-alive");
		request.setHeader("Accept-Encoding", "gzip, deflate, br");
		request.setHeader("Content-Type", "application/json");
		request.setHeader("Host", "m.douban.com");
		request.setHeader("Accept", "https://m.douban.com/book/subject/34262174/?refer=home");
		request.setHeader("Referer", "application/json");
		request.setHeader("Accept-Language", "zh-cn");
		request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1");
		request.setHeader("X-Requested-With", "XMLHttpRequest");
	}

	public static String parseParams(Map<String, String> params) {
		if (params == null || params.isEmpty()) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		for (String key : params.keySet()) {
			sb.append(key + "=" + params.get(key) + "&");
		}
		return sb.substring(0, sb.length() - 1);

	}
	
	/**
     * 向目的URL发送get请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
	public static String getStrRequest(String url, Map<String, String> params){
    	try {
    		Thread.sleep(666);
		} catch (Exception e) {
		}
    	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    	requestFactory.setConnectTimeout(3000);// 设置超时
    	requestFactory.setReadTimeout(3000);
        RestTemplate client = new RestTemplate(requestFactory);
        String str = client.getForObject(url, String.class,  params);
        return decodeUnicode(str);
    }
	
	/**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
	public static JSONObject sendPostRequest(String url, Map<String, String> params, MediaType contentType){
    	try {
    		Thread.sleep(666);
		} catch (Exception e) {
		}
        RestTemplate client = new RestTemplate();
        HttpEntity<Map<String, String>> requestEntity = null;
        if(contentType != null) {
        	HttpHeaders headers = new HttpHeaders();
        	headers.setContentType(contentType);
        	//将请求头部和参数合成一个请求
        	requestEntity = new HttpEntity<>(params, headers);
        }else {
        	requestEntity = new HttpEntity<>(params);
        }
        
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        return client.postForObject(url, requestEntity, JSONObject.class);
    }

	public static String decodeUnicode(final String unicode) {
		StringBuffer string = new StringBuffer();

		String[] hex = unicode.split("\\\\u");

		for (int i = 0; i < hex.length; i++) {

			try {
				// 汉字范围 \u4e00-\u9fa5 (中文)
				if(hex[i].length()>=4){//取前四个，判断是否是汉字
					String chinese = hex[i].substring(0, 4);
					try {
						int chr = Integer.parseInt(chinese, 16);
						boolean isChinese = isChinese((char) chr);
						//转化成功，判断是否在  汉字范围内
						if (isChinese){//在汉字范围内
							// 追加成string
							string.append((char) chr);
							//并且追加  后面的字符
							String behindString = hex[i].substring(4);
							string.append(behindString);
						}else {
							string.append(hex[i]);
						}
					} catch (NumberFormatException e1) {
						string.append(hex[i]);
					}

				}else{
					string.append(hex[i]);
				}
			} catch (NumberFormatException e) {
				string.append(hex[i]);
			}
		}

		return string.toString();
	}

	/**
	 * 判断是否为中文字符
	 *
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

}
